# -*- coding: utf-8 -*-
# Version: Python 3.9.7
# Author: TRIX
# Date: 2021-11-21 10:24:03
# Use: 尝试寻找测试的答案 F12 复制测试所在源码的body元素 并提供查找题目的正则表达式

from selenium import webdriver#浏览器驱动器
from msedge.selenium_tools import EdgeOptions#Edge浏览器配置
from selenium.webdriver.common.by import By#locator 参数
from selenium.webdriver.common.keys import Keys#按键
from selenium.webdriver.support import expected_conditions as EC#条件判断
from selenium.webdriver.support.wait import WebDriverWait#网络等待
from time import sleep

import re
import pyperclip

def openDriver(BrowserPath=r'C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe',insecure=False,headless=False):
	'''打开浏览器驱动器
	BrowserPath 浏览器路径
	insecure 是否为不安全模式
	headless 是否为无界面模式'''
	driverOptions = EdgeOptions()#Edge浏览器配置
	driverOptions.use_chromium = True#使用chormium内核
	if insecure:#如果为不安全模式
		driverOptions.add_argument('--allow-running-insecure-content')#允许不安全内容
		driverOptions.add_argument("--ignore-certificate-errors")#忽略证书错误
	if headless:#如果为无界面模式
		driverOptions.add_argument('headless')#无界面
		driverOptions.add_argument('disable-gpu')#禁用GPU
	driver = webdriver.Chrome(executable_path=BrowserPath, options=driverOptions)#启动浏览器驱动器
	return driver#返回浏览器驱动器对象 并启动

def getAnswer(siteInfoDict):
	#获取题目
	text=pyperclip.paste()
	questions=re.compile(siteInfoDict['rePattern'],re.S+re.M).findall(text)
	print(f'获取到的问题有{len(questions)}个')
	if not len(questions):
		print('可能是 未正确复制网页源码 或 正则表达式不匹配源码\nF12 复制测试所在源码的body元素 并提供查找题目的正则表达式')
		return

	for i,n in enumerate(questions):
		questions[i]=''.join(n[1:-1]).replace('</p>','').replace('<p class="q-cnt crt mul">','')

	with open('questions.txt','w',encoding='utf-8') as f:#保存题目
		f.write('\n'.join(questions))

	#搜索答案
	qas=[]#问答列表
	noAns=0#未搜索到答案的次数
	for i,question in enumerate(questions):
		print(f'\n第{i+1}题\n')
		try:
			driver.get(siteInfoDict['basicUrl'])#转到链接
			wait.until(EC.presence_of_element_located((By.TAG_NAME,'input')))
			driver.find_element(By.TAG_NAME,'input').send_keys(question.split('(')[0])
			wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'body > div.container.xs-top-15 > div > div > div:nth-child(1) > div > div > div > p:nth-child(2) > button:nth-child(1)')))
			driver.find_element(By.CSS_SELECTOR,'body > div.container.xs-top-15 > div > div > div:nth-child(1) > div > div > div > p:nth-child(2) > button:nth-child(1)').click()

			wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'body > div.container.xs-top-15 > div > div > div:nth-child(4) > div > div.content > div > ul > li > a')))
			qasText=driver.find_element(By.CSS_SELECTOR,'body > div.container.xs-top-15 > div > div > div:nth-child(4) > div > div.content > div > ul > li > a').click()#点击后页面会跳转

			driver.switch_to.window(driver.window_handles[-1])#切换到最新页面 用于元素定位

			wait.until(EC.presence_of_element_located((By.XPATH,'/html/body/div[1]/div/div/div[3]/div/div/div[1]/div[2]/p')))
			qasText=driver.find_element(By.XPATH,'/html/body/div[1]/div/div/div[3]/div/div/div[1]/div[2]/p').text.replace('\n\n\n','\n').replace('\n\n','\n')

			qas.append(qasText)
			driver.close()#关闭当前页面
			driver.switch_to.window(driver.window_handles[0])#切换到初始页面
			print(qasText)
		except Exception:
			qas.append('{} 该题未搜到答案'.format(question))
			print('该题未搜到答案')
			noAns+=1
			continue
		sleep(3)#网站有搜索间隔3s限制
	driver.quit()
	brief=f'共{len(questions)}道题 共{noAns}道题未搜素到答案 解答率为{1-round(noAns/len(questions),3)}\n若为百分制 将获取{100*(1-round(noAns/len(questions),3))}分'
	print(brief)
	with open('Q&As.txt','w',encoding='utf-8') as j:
		j.write(brief+'\n')
		for i,qa in enumerate(qas):
			j.write(str(i+1)+'.'+qa+'\n\n')

driver=openDriver(headless=True)#启动浏览器驱动器
wait=WebDriverWait(driver, 5)#设置等待 超时时间
siteInfoDict={#信息
'basicUrl':'https://www.jhq8.cn/',
'rePattern':r'<p class="q-cnt crt">(.*?)<span>\[2分\]</span> <p class="q-cnt crt">(.*?)(</p></p><ol><li>|</p><ol class="true-or-false"><li>)',
}
getAnswer(siteInfoDict)
